<template>
  <view style="background-color: #f7f7f7;">
    <view class="top">
      <view class="back-btn" @click="backPage()">
        <view class="back-icon"></view>
      </view>
      <view style="text-align: center; font-size: 35rpx; color: #fff;">经营统计</view>
      <view class="card">
        <view class="uni-padding-wrap uni-common-mt">
          <uni-segmented-control :current="current" :values="items" :style-type="styleType"
                                 :active-color="activeColor" @clickItem="onClickItem"/>
        </view>
        <view class="line"></view>
        <!-- 收入和订单量统计 -->
        <view class="statistics">
          <view class="stat-item">
            <image src="/static/income.png"
                   style="width: 35rpx; height: 30rpx; background-color: #ff521b; padding: 10rpx;"></image>
            <view class="amount">￥{{ income }}</view>
            <view class="label">收入</view>
          </view>
          <view class="stat-item">
            <image src="/static/num.png"
                   style="width: 35rpx; height: 30rpx; background-color: #378ffd; padding: 10rpx;"></image>
            <view class="amount">{{ orderCount }}</view>
            <view class="label">订单量</view>
          </view>
        </view>
      </view>
      <view class="card">
        <view class="income-chart">
          <text class="chart-title">收入分布</text>
          <view class="line2"></view>
          <view class="charts-box">
            <qiun-data-charts
                type="pie"
                :opts="pieOpts"
                :chartData="pieChartData"
            />
          </view>
        </view>
      </view>

      <view class="card">
        <view class="order-chart">
          <text class="chart-title">订单分布</text>
          <view class="line2"></view>
          <view class="charts-box">
            <qiun-data-charts
                type="column"
                :opts="columnOpts"
                :chartData="columnChartData"
            />
          </view>
        </view>
      </view>
    </view>
    <view style="height: 1000rpx;"></view>
  </view>

</template>

<script setup>
import { ref, onMounted } from 'vue';
import baseUrl from '../../utils/urlConfig.js';

// 从原 Vue 2 代码迁移过来的响应式数据
const items = ref(['今日', '昨日', '一周']);
const styles = ref([
  {
    value: 'button',
    text: '按钮',
    checked: true
  },
  {
    value: 'text',
    text: '文字'
  }
]);
const colors = ref(['#007aff', '#4cd964', '#dd524d']);
const current = ref(0);
const colorIndex = ref(0);
const activeColor = ref('#007aff');
const styleType = ref('text');

const userInfo = uni.getStorageSync('info');
const records = ref([]);
const income = ref(0);
const orderCount = ref(0);

// 原有的饼图相关响应式数据
const pieChartData = ref({});
const pieOpts = ref({
  color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"], 
  padding: [5,5,5,5], 
  enableScroll: false, 
  extra: { 
    pie: { 
      activeOpacity: 0.5, 
      activeRadius: 10, 
      offsetAngle: 0, 
      labelWidth: 15, 
      border: false, 
      borderWidth: 3, 
      borderColor: "#FFFFFF" 
    } 
  } 
});

// 新增柱状图相关响应式数据
const columnChartData = ref({});
const columnOpts = ref({
  color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"], 
  padding: [15,15,0,5], 
  enableScroll: false, 
  legend: {}, 
  xAxis: { 
    disableGrid: true 
  }, 
  yAxis: { 
    data: [ 
      { 
        min: 0 
      } 
    ] 
  }, 
  extra: { 
    column: { 
      type: "group", 
      width: 30, 
      activeBgColor: "#000000", 
      activeBgOpacity: 0.08 
    } 
  } 
});

// 从原 Vue 2 代码迁移过来的方法
const onClickItem = (e) => {
  if (current.value !== e.currentIndex) {
    current.value = e.currentIndex;
  }
  // 时间选择变化时，重新处理数据
  processData();
};

const backPage = () => {
  uni.navigateBack();
};

const fetchData = () => {
  uni.request({
    url: baseUrl + '/yyq/record/listByMid/' + userInfo.mid,
    header: {
      Authorization: uni.getStorageSync('token')
    },
    success: res => {
      console.log('获取成功', res.data.data);
      records.value = res.data.data;
      // 数据获取成功后，处理数据
      processData();
    },
  })
};

// 处理数据的函数
const processData = () => {
  const selectedTime = items.value[current.value];
  let filteredRecords = [];

  const now = new Date();
  switch (selectedTime) {
    case '今日':
      const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      filteredRecords = records.value.filter(record => {
        const recordTime = new Date(record.time);
        return recordTime >= todayStart;
      });
      getPieServerData(filteredRecords);
      getColumnServerData(filteredRecords);
      break;
    case '昨日':
      const yesterdayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
      const yesterdayEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      filteredRecords = records.value.filter(record => {
        const recordTime = new Date(record.time);
        return recordTime >= yesterdayStart && recordTime < yesterdayEnd;
      });
      getPieServerData(filteredRecords);
      getColumnServerData(filteredRecords);
      break;
    case '一周':
      const oneWeekAgo = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 7);
      filteredRecords = records.value.filter(record => {
        const recordTime = new Date(record.time);
        return recordTime >= oneWeekAgo;
      });
      getPieServerData(filteredRecords);
      getColumnServerData(filteredRecords);
      break;
  }

  // 计算收入和订单量
  income.value = filteredRecords.reduce((sum, record) => sum + Number(record.price), 0);
  orderCount.value = filteredRecords.length;
};

// 模拟从服务器获取饼图数据
const getPieServerData = (filteredData) => {
  // 假设 filteredData 中的数据包含 serviceTypeName 和 price 字段
  const data = filteredData.map(record => ({
    name: record.serviceTypeName,
    value: Number(record.price)
  }));

  let res = {
    series: [
      {
        data: data
      }
    ]
  };
  pieChartData.value = JSON.parse(JSON.stringify(res));
};

const getColumnServerData = (filteredData) => {
  const categories = filteredData.map(record => record.serviceTypeName);
  const seriesData = filteredData.map(record => Number(record.price));
  let res = {
    categories: categories, 
    series: [
      {
        name: "订单数",
        data: seriesData
      }
    ] 
  };
  columnChartData.value = JSON.parse(JSON.stringify(res));
};
//获取完成订单列表
function orderwlist(){
	uni.request({
	  url: baseUrl + '/yyq/orders/getlistes',
	  header: {
	    Authorization: uni.getStorageSync('token')
	  },
	  success: res => {
	    console.log('获取成功完成订单列表', res);
	  },
	})
	uni.request({
	  url: baseUrl + '/yyq/orders/getlistes1',
	  header: {
	    Authorization: uni.getStorageSync('token')
	  },
	  success: res1 => {
	    console.log('获取成功完成订单列表1', res1);
	  },
	})
}
// 页面加载时获取数据
onMounted(() => {
  fetchData();
	orderwlist();
});
</script>

<style>
@import "@/common/app.css";

.card {
  border-radius: 20px;
  background-color: #fff;
  margin: 30rpx;
  padding: 30rpx 20rpx;
}

.line {
  width: 100%;
  height: 1px;
  background-color: gray;
  margin: 20rpx 10rpx;
}

.line2 {
  width: 100%;
  height: 2px;
  background-color: gray;
  margin: 20rpx 10rpx;
}

.date-selector {
  display: flex;
  justify-content: center;
  margin-bottom: 20rpx;
}

.date-selector .select-item {
  padding: 10rpx 20rpx;
  border-radius: 5rpx;
  cursor: pointer;
}

.date-selector .select-item.active {
  background-color: #2c82ff;
  color: white;
}

.statistics {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20rpx;
}

.stat-item {
  text-align: center;
  margin: 40rpx 0;
}

.amount {
  font-size: 32rpx;
  margin-bottom: 10rpx;
}

.label {
  font-size: 24rpx;
}

.chart-title {
  font-size: 28rpx;
}

.chart-canvas {
  width: 100%;
  height: 200rpx;
}

.uni-common-mt {
  margin-top: 30px;
}

.content {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  justify-content: center;
  align-items: center;
  height: 150px;
  text-align: center;
}

.content-text {
  font-size: 14px;
  color: #666;
}

.color-tag {
  width: 25px;
  height: 25px;
}

.back-btn {
  margin-left: 20rpx;
  width: 50rpx;
  height: 50rpx;
  position: relative;
}

.back-icon {
  width: 30px;
  height: 30px;
}

.back-icon::before {
  content: "";
  position: absolute;
  width: 20px;
  height: 2px;
  background-color: #fff;
  top: 80rpx;
  left: 47rpx;
  transform: translate(-50%, -50%);
}

.back-icon::after {
  content: "";
  position: absolute;
  width: 10px;
  height: 10px;
  border-left: 2px solid #fff;
  border-bottom: 2px solid #fff;
  transform: rotate(45deg);
  top: 70rpx;
  left: 30rpx;
}

.charts-box {
  width: 100%;
  height: 300px;
}
</style>